package medium;

import java.util.ArrayList;
import java.util.List;

public class Lc113 {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        private List<List<Integer>> ret = new ArrayList<>();

        private int target = 0;

        public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
            this.target = targetSum;
            dfs(root, new ArrayList<>(), 0);
            return ret;
        }

        void dfs(TreeNode node, List<Integer> path, int curSum) {
            if (node == null) {
                return;
            }
            if (node.left == null && node.right == null) {
                if (curSum + node.val == target) {
                    path.add(node.val);
                    ret.add(new ArrayList<>(path));
                }
            }

            path.add(node.val);
            curSum += node.val;
            if (node.left != null) {
                dfs(node.left, new ArrayList<>(path), curSum);
            }
            if (node.right != null) {
                dfs(node.right, new ArrayList<>(path), curSum);
            }
        }
    }
}